package net.disy.cadenza.repository.workflow;

import net.disy.cadenza.repository.wrappers.SelectorWrapper;
import net.disy.cadenza.repositorytree.schema.Item;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Workflow {
	public static String WORKFLOW_ASYNCHRONOUS = "asynchronous";
	public static String WORKFLOW_SOURCE = "source";
	public static String WORKFLOW_TEMPLATE = "template";
	private final String WORKFLOW_ID_TEMPLATE = "Show.RepositoryItem.Id=%s&";

	private boolean asynchronous;
	private Source source;
	private Template template;
	private String name;
	private Item item;
	private boolean baseWorkflow = false;
	private SelectorWrapper selector;
	
	public Workflow(Document document, String name){
		this.name = name;
		Node workflowNode = document.getDocumentElement();
		NamedNodeMap namedNodeMap = workflowNode.getAttributes();
		Node attrNode = namedNodeMap.getNamedItem(WORKFLOW_ASYNCHRONOUS);
		asynchronous = (attrNode != null) ? Boolean.parseBoolean(attrNode.getNodeValue()) : false;
		NodeList workflowChildNodes = workflowNode.getChildNodes();
		Node currentNode;
		for(int i = 0 ; i < workflowChildNodes.getLength() ; i ++){
			currentNode  = workflowChildNodes.item(i);
			if(currentNode.getNodeType() == Node.ELEMENT_NODE){
				if(currentNode.getNodeName().equalsIgnoreCase(WORKFLOW_SOURCE)){
					source = new Source(currentNode);
					continue;
				}
				if(currentNode.getNodeName().equalsIgnoreCase(WORKFLOW_TEMPLATE)){
					template = new Template(currentNode);
					continue;
				}
			}
		}
	}
	
	public String getName() {
		return name;
	}
	
	public boolean isAsynchronous() {
		return asynchronous;
	}

	public Source getSource() {
		return source;
	}

	public Template getTemplate() {
		return template;
	}

	public Item getItem() {
		return item;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	public boolean isBaseWorkflow() {
		return baseWorkflow;
	}

	public void setBaseWorkflow(boolean baseWorkflow) {
		this.baseWorkflow = baseWorkflow;
	}
	
	public String getSelectorName(){
		if(source != null )
			return source.getResultSourceData().getSelectorName();
		return null;
	}
	
	public SelectorWrapper getSelector() {
		return selector;
	}

	public void setSelector(SelectorWrapper selector) {
		this.selector = selector;
	}


	public String getURL(){
		return String.format(WORKFLOW_ID_TEMPLATE, getItem().getId());
	}
	
}
